<template>
  <div class="article_box">
    <div class="article_box_total" v-if="articleSearchValue.trim() != ''">
      <span>{{ '搜索结果包含" ' }}</span>
      <span>{{ articleSearchValue }}</span>
      <span>{{ ' "的信息共' + articleTotal + "条" }}</span>
    </div>
    <div :class="['article_list', { active: articleSearchValue.trim() == '' }]" v-if="!article_editor_show">
      <div class="article_list_common" v-for="(articleItem, index) in list" :key="index + 'articleList'" @mouseenter.stop.prevent="mouseenterFn(articleItem)" @mouseleave.stop.prevent="mouseleaveFn(articleItem)"
        @click.stop.prevent="openLinkFn(articleItem)">
        <div class="article_list_common_left">
          <div class="article_list_common_t">
            {{
                articleItem.articleTitle.length > 34
                  ? articleItem.articleTitle.substring(0, 34) + "..."
                  : articleItem.articleTitle
            }}
          </div>
          <div class="article_list_common_m">
            {{
                articleItem.articleEditor.length > 40
                  ? articleItem.articleEditor.substring(0, 40) + "..."
                  : articleItem.articleEditor
            }}
          </div>
          <div class="article_list_common_f">
            <img v-if="articleItem.sendId == myInfo.id" src="static/image/home/article/publisher_me.png" />
            <img v-else src="static/image/home/article/publisher_others.png" />
            <span>{{ "发布" }}</span>
            <span>{{
                articleItem.sendId == myInfo.id ? "我自己" : articleItem.sendName
            }}</span>
            <img v-if="articleItem.sendId == myInfo.id && articleItem.receiveUser" src="static/image/home/article/receiveUser.png" />
            <span style="margin: 0 20px 0 6px;" v-if="articleItem.sendId == myInfo.id && articleItem.receiveUser">
              对象
            </span>
            <span style="" v-if="articleItem.sendId == myInfo.id && articleItem.receiveUser">
              {{articleItem.receiveUser}}
            </span>
            <span>{{ parseInt(articleItem.time) | getTimeAll }}</span>

          </div>
        </div>
        <div class="article_list_common_right">
          <div v-if="articleItem.isRecal && articleItem.sendId == myInfo.id" class="article_list_common_right_recallImg" @click.stop.prevent="revocationArticleFn(articleItem)"></div>
          <div v-else class="article_list_common_right_recallImg_trim"></div>
          <img v-if="!$isNull(articleItem.articleImgUrl)" class="imgPath" :src="articleImgUrl + articleItem.articleImgUrl" />
          <el-button icon="el-icon-delete" circle @click.stop.prevent="deleteArticleInit(articleItem)"></el-button>
        </div>

      </div>
    </div>
    <div class="article_editor" v-if="article_editor_show">
      <div class="article_editor_t common" @contextmenu="copyRignt($event)">
        <label>{{ `标题` }}</label>
        <input ref="article_title" type="text" placeholder="请输入标题" v-model="article_title" />
       
      </div>
      <div class="article_editor_p common" @click.stop.prevent="getArticleUser">
        <label>{{ "接收人" }}</label>
        <input type="text" placeholder="请选择接收人" v-model="article_user_name" readonly />
        <img src="static/image/home/add_processed.png" />
      </div>
      <div class="article_editor_u common" @contextmenu="copyRignt($event)">
        <label>{{ "链接地址" }}</label>
        <input ref="article_url" type="text" placeholder="请输入链接地址" v-model="article_url" />
      </div>
      <div class="article_editor_i common" @contextmenu="copyRignt($event)">
        <label>{{ "文章简介" }}</label>
        <textarea @paste="handlePaste" ref="article_editor" placeholder="请输入简介内容..." v-model="article_editor"></textarea>

      </div>
      <div class="article_editor_m common">
        <label>{{ "缩略图" }}</label>
        <div class="article_editor_m_wrap">
          <div class="article_editor_m_wrap_m" @click="get_file_value">
            <img class="update_img" ref="input_file" src="static/image/home/article/add_pic.png" />
            <span>{{ "上传缩略图" }}</span>
            <img v-if="article_img_url" class="delete_img" @click.stop.prevent="deleteImgFn" src="static/image/home/article/pic_delete.png" />
          </div>
          <div class="article_editor_m_wrap_l" v-if="UpLoadFileLoading">
            <img src="static/image/home/article/Aloading.gif" />
          </div>
        </div>
      </div>
      <div class="article_editor_button">
        <div @click.stop.prevent="articleShareFn">{{ "分享" }}</div>
        <div @click.stop.prevent="articleCloseFn">{{ "取消" }}</div>
      </div>

    </div>
    <div class="article_publish" v-if="!article_editor_show && myInfo.article == '1'" @click.stop.prevent="publishTextFn">
      <img src="static/image/home/article/publish.png" />
      <span>{{ "我要发布文章" }}</span>
    </div>
    <div class="copy_paste_btn" v-if="copyShow" :style="{ top: pasteMenuTop + 'px', left: pasteMenuLeft + 'px' }">
      <span @click.stop.prevent="copyValue($event)">复制</span>
      <span @mousedown="copyMain($event)">粘贴</span>
    </div>
  </div>
</template>
<script>
import { shareArticle } from "@/api/articleList";
export default {
  props: {
    list: {
      type: Array,
      default: () => {
        return [];
      },
    },
    articleSendList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    article_editor_show: {
      type: Boolean,
      default: false,
    },
    articleTotal: {
      type: Number,
      default: 0,
    },
    articleSearchValue: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      copyText: "",
      copyShow: false,
      pasteMenuTop: 0,
      pasteMenuLeft: 0,
      recalShow: false,
      article_user_name: "",
      article_user_id: [],
      article_title: "",
      article_url: "",
      article_editor: "",
      article_img_url: "",
      UpLoadFileLoading: false,
    };
  },
  computed: {
    myInfo() {
      return this.$store.state.myInfo;
    },
    isArticleId() {
      return this.$store.state.isArticleId;
    },
    articleImgUrl() {
      return this.$store.state.url + "api/v1/oim/image/download.do?id=";
    },
  },
  watch: {
    articleSendList() {
      let nameList = [],
        idList = [];
      this.articleSendList.map((item) => {
        nameList.push(item.NAME || item.name || item.LEABLE);
        idList.push({
          // 1 部门 0 人
          type: item.FID ? "1" : "0",
          value: item.FID || item.id || item.ID,
        });
      });
      this.article_user_name = nameList.join();
      this.article_user_id = idList;
    },
    isArticleId() {
      console.log(this.isArticleId, "isArticleIdisArticleId");
      if (this.isArticleId && this.$refs.input_file) {
        this.UpLoadFileLoading = false;
        this.article_img_url = this.$refs.input_file.src =
          this.articleImgUrl + this.isArticleId;
        console.log(
          this.article_img_url,
          "this.article_img_urlthis.article_img_url"
        );
      }
    },
    article_editor_show() {
      if (!this.article_editor_show) {
        this.UpLoadFileLoading = false;
        this.closeImgUrl();
        this.closeEditor();
      }
    },
  },
  mounted() {
    const domClick = () => {
      this.copyShow = false;
    };
    document.addEventListener("click", domClick);
    this.$once("hook:beforeDestroy", () => {
      document.removeEventListener("click", domClick);
    });
  },
  methods: {
    handlePaste(e) {
      console.log(e, 204);
    },

    copyValue(e) {
      this.copyShow = false;

      // 到粘贴板
      // 2022/6/21空内容复制判断
      if (this.copyText == "") return this.$Message.warning("复制内容为空");
      this.pasteVal = this.copyText;
      if (window.navigator.clipboard) {
        window.navigator.clipboard.writeText(this.copyText).then(
          () => {
            this.$Message.success("内容已复制到粘贴板");
          },
          () => {
            console.log("失败");
          }
        );
      } else {
        let value = this.copyText;
        let ipt = document.createElement("input");
        ipt.value = value;
        document.body.appendChild(ipt);
        ipt.select();
        document.execCommand("Copy");
        this.$Message.success("内容已复制到粘贴板");
        ipt.remove();
      }
    },
    copyMain(e) {
      e.preventDefault();
      console.log(this.copyText, 232);
      document.execCommand("insertText", false, this.pasteVal);
    },
    // 右键
    copyRignt(e) {
      let target;
      if (e.target == this.$refs.article_editor) {
        target = "article_editor";
      } else if (e.target == this.$refs.article_title) {
        target = "article_title";
      } else if (e.target == this.$refs.article_url) {
        target = "article_url";
      }
      console.log(
        this.$refs.article_editor.selectionStart,
        this.$refs.article_editor.selectionEnd
      );
      this.getItemCoordinate(e);
      this.copyShow = true;

      this.$forceUpdate();
      this.copyText = "";
      // var selection = document.getSelection()
      // var selectionText = selection.toString().trim()
      // console.log(selectionText.trim(), 86);
      console.log(this.getSelectedContext(target), 256);
      if (this.getSelectedContext(target)) {
        this.copyText = this.getSelectedContext(target);
      }
    },
    //获取选区文本
    getSelectedContext(target) {
      return this[target].substring(
        this.$refs[target].selectionStart,
        this.$refs[target].selectionEnd
      );
    },
    //获取坐标位置
    getItemCoordinate(e) {
      this.pasteMenuTop = e.clientY - 10 || 0;
      this.pasteMenuLeft = e.clientX - 10 || 0;
    },
    publishTextFn() {
      this.$emit("changeEditor", true);
    },
    articleShareFn() {
      let Expression = new RegExp(
        /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/
      );
      if (this.article_title.trim() == "") {
        this.$Message.warning("请输入标题");
        return;
      } else if (this.article_user_id.length == 0) {
        this.$Message.warning("请选择分享的人");
        return;
      } else if (this.article_url.trim() == "") {
        this.$Message.warning("请输入链接");
        return;
      } else if (!Expression.test(this.article_url)) {
        this.$Message.warning("请输入有效链接");
        return;
      } else if (this.article_editor.trim() == "") {
        this.$Message.warning("请完善简介");
        return;
      }
      let initid = this.$func.uuid();
      shareArticle({
        userId: this.myInfo.id,
        members: JSON.stringify(this.article_user_id),
        articleId: initid,
        article: JSON.stringify({
          articleLink: this.article_url,
          updateDate: new Date().getTime(),
          describe: this.article_editor,
          id: initid,
          title: this.article_title,
          picture: this.isArticleId,
        }),
      })
        .then((res) => {
          if (res.resp_code == 0) {
            this.$emit("getArticleList");
            this.$emit("changeEditor", false);
            this.$Message.success(res.resp_msg);
            this.closeEditor();
            this.closeImgUrl();
          } else {
            {
              this.$Message.warning(res.resp_msg);
            }
          }
        })
        .catch((error) => {
          this.$Message.warning(error.resp_msg);
        });
    },
    articleCloseFn() {
      this.articleSendList = [];
      this.$emit("changeEditor", false);
    },
    get_file_value() {
      let info = this.$shell("OpenFileDialog_Invoke", [0]);
      let initId = this.$func.uuid();
      info = JSON.parse(info);
      const path = require("path");

      if (path.extname(info.return_data[0].FilePath) == ".gif")
        return this.$Message.warning("gif格式禁止上传");
      switch (path.extname(info.return_data[0].FilePath)) {
        case ".jpg":
        case ".jpeg":
        case ".png":
          console.log(1111111);
          break;
        default:
          return this.$Message.warning("只能上传图片");
      }

      let res = this.$shell("UpLoadArticleFile", [
        "0",
        "",
        initId,
        info.return_data[0].FilePath,
        0,
        "",
        this.myInfo.id,
      ]);
      this.UpLoadFileLoading = true;
      // try {
      //   res = JSON.parse(res);
      //   if (res.return_code != "TRUE") {
      //     this.$Message.warning(res.return_msg);
      //   } else {
      //     this.UpLoadFileLoading = true;
      //   }
      // } catch (err) {
      //   this.$Message.warning("上传文件出错,请稍后再试");
      // }
    },
    updateArtFileStatus(isSuccess, fileId, fileName) {
      console.log("文件上传返回", isSuccess, fileId, fileName);
      let _this = this;
      if (isSuccess == 0) {
        this.UpLoadFileLoading = false;
        return this.$Message.warning("上传文件出错,请稍后再试");
      }
      this.$store.state.isArticleId = fileId;
      this.UpLoadFileLoading = false;
      // this.$downLoad(
      //   "api/v1/oim/image/download.do",
      //   fileId,
      //   (wt) => {
      //     var fileReader = new FileReader();
      //     fileReader.onload = function (w) {
      //       let base64 = w.target.result.replace(
      //         /^data\:.{1,40}base64\,/gi,
      //         ""
      //       );
      //       let arr = fileName.split(".").splice(-1)[0];
      //       let info = _this.$shell("SaveFileStream", [
      //         _this.myInfo.id,
      //         base64,
      //         arr,
      //       ]);
      //       console.log('info',info)
      //       info = JSON.parse(info);

      //     };
      //     fileReader.readAsDataURL(wt);
      //   },
      //   (wt) => {
      //     console.log("error");
      //     console.log(wt);
      //   }
      // );
    },
    deleteImgFn() {
      this.$refs.input_file.src = require("../../../static/image/home/article/add_pic.png");
      this.closeImgUrl();
    },
    closeImgUrl() {
      this.article_img_url = "";
      this.$store.commit("Is_Article_Id", "");
      this.$forceUpdate();
    },
    closeEditor() {
      this.article_title = this.article_url = this.article_editor = "";
      this.$forceUpdate();
    },
    getArticleUser() {
      this.$emit("setModalFirst", 8);
    },
    mouseenterFn(articleItem) {
      this.$set(articleItem, "isRecal", true);
      this.$forceUpdate();
    },
    mouseleaveFn(articleItem) {
      this.$set(articleItem, "isRecal", false);
      this.$forceUpdate();
    },
    openLinkFn(articleItem) {
      this.$emit("openLinkFn", articleItem);
    },
    // 撤销
    revocationArticleFn(articleItem) {
      this.$emit("revocationArticleFn", articleItem);
    },
    // 2022/7/26 新增 删除文章
    deleteArticleInit(articleItem) {
      this.$emit("deleteArticleInit", articleItem.articleMessage);
    },
  },
  created() {
    window.updateArtFileStatus = this.updateArtFileStatus;
  },
};
</script>
<style lang="less" scoped>
.copy_paste_btn {
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
  font-size: 1.2em;
  color: #fff;
  cursor: pointer;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  & > span {
    padding: 0.7em;
    &:hover {
      background: #999;
    }
  }
}
</style>
